package com.lechuang.mq.core;

import com.lechuang.common.constant.BaseConstant;
import com.lechuang.mq.listenter.MqListener;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.slf4j.MDC;
import org.springframework.amqp.core.Message;

/**
 *
 * @author zyf
 */
@Log4j2
public class BaseRabbiMqHandler<T> {
    public void onMessage(T t, Long deliveryTag, Channel channel, Message message, MqListener<T> mqListener) {
        try {
            String traceId = (String) message.getMessageProperties().getHeaders().get(BaseConstant.TRACE_ID);
            MDC.put(BaseConstant.TRACE_ID, traceId);
            mqListener.handler(t, channel);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("onMessage is error", e);
            try {
                //不确认消息,参数1：消息，参数2：是否应用于多消息，参数3：是否重新放回队列，否则丢弃或者进入死信队列
                channel.basicNack(deliveryTag, false, false);
            } catch (Exception ex) {
                log.error("onMessage is error", ex);
                throw new RuntimeException(ex);
            }
        }finally {
            MDC.clear();
        }
    }
}
